package com.scpii.universal.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.scpii.universal.hibernate.entity.AppSearchFields;
import com.scpii.universal.hibernate.entity.AppsSearch;
import com.scpii.universal.hibernate.entity.SearchField;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XmlUtil {

	private static XStream xstream;
	static {
		// 获得当前Class对象
		xstream = new XStream(new DomDriver());
		// xml中的tagName与类名的对应
		xstream.alias("apps", AppsSearch.class);
		xstream.alias("app", AppSearchFields.class);
		xstream.alias("attr", SearchField.class);
		// xml中属性名与对象中属性名称的对应
		xstream.aliasAttribute(AppSearchFields.class, "intAppId", "intAppId");
		xstream.aliasAttribute(SearchField.class, "intAttrId", "intAttrId");
	}

	/**
	 * 根据文件读取
	 * 
	 * @author Taylor 2012-9-20 上午11:27:19
	 * @param fileName
	 * @return Object
	 * @throws IOException
	 */
	public static Object readFromXml(String fileName) throws IOException {
		ResourceLoader resourceLoader = new DefaultResourceLoader();
		Resource resource = resourceLoader.getResource("classpath:" + fileName);
		InputStream in = resource.getInputStream();
		Object obj = xstream.fromXML(in);
		return obj;
	}

	/**
	 * 写进文件
	 * 
	 * @author Taylor 2012-9-20 上午11:27:39
	 * @param obj
	 * @param fileName
	 *            void
	 */
	public static void writeToXml(Object obj, String fileName) {
		try {
			PrintWriter pw = new PrintWriter(fileName, "UTF-8");
			xstream.toXML(obj, pw);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public static AppsSearch getAppSearchFields(String fileName) {
		try {
			return (AppsSearch) XmlUtil.readFromXml(fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<SearchField> getAppSearchFields(int appId) {
		AppsSearch apps = getAppSearchFields("SearchField.xml");
		if (apps != null) {
			List<AppSearchFields> lstAppSearch = apps.getLstAppSearchFields();
			for (AppSearchFields appSearchFields : lstAppSearch) {
				if (appSearchFields.getIntAppId() == appId)
					return appSearchFields.getLstSearchFields();
			}
		}
		return null;
	}

	public static void main(String[] args) {
		List<SearchField> lstField = XmlUtil.getAppSearchFields(1289);
		for (SearchField searchField : lstField) {
			System.out.println("属性ID：" + searchField.getIntAttrId());
			System.out.println("属性类型：" + searchField.getIntType());
			System.out.println("属性输入类型：" + searchField.getIntInputType());
			System.out.println("属性名：" + searchField.getVarAttrName());
		}
	}
}
